package cn.haoran.modules.palaeobios.service.impl;

import cn.haoran.common.utils.DateUtils;
import cn.haoran.modules.palaeobios.entity.LogEntity;
import cn.haoran.modules.palaeobios.entity.LogSheetEntity;
import cn.haoran.modules.palaeobios.service.LogSheetService;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.DateOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LogSheetServiceImpl implements LogSheetService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public List<LogSheetEntity> findAll() {
        return mongoTemplate.findAll(LogSheetEntity.class);
    }

    @Override
    public List<LogSheetEntity> findByDate(String date) {
        Query query = new Query(Criteria.where("createDate").regex(date));
        return mongoTemplate.find(query,LogSheetEntity.class);
    }

    @Override
    public List<LogSheetEntity> countMun() {
        List<String> dateList = getWeekData();
        Aggregation agg = Aggregation.newAggregation(
                // 第一步：挑选所需的字段，类似select *，*所代表的字段内容
                Aggregation.project("createDate"),
                // 第二步：sql where 语句筛选符合条件的记录
                Aggregation.match(
                        Criteria.where("createDate").in(dateList)
                                ),
                // 第三步：分组条件，设置分组字段
                Aggregation.group("createDate")
                        .count().as("allCount")
                        .last("createDate").as("createDate")
                ,
                // 增加publishDate为分组后输出的字段
                // 第四步：重新挑选字段
                Aggregation.project("createDate","allCount")
        );
        AggregationResults<LogSheetEntity> results = mongoTemplate.aggregate(agg, "log_sheet", LogSheetEntity.class);
        List<LogSheetEntity> list = results.getMappedResults();
        return list;
    }
    /**
     * 获得当前日子的前7天时间
     */
    private List<String> getWeekData(){
        List<String> list = new LinkedList<>();
        Date date = DateUtil.date();
        list.add(DateUtil.today());
        for (int i = 0; i < 4; i++) {
            date = DateUtil.offsetDay(date, -1);
            String time = DateUtil.formatDate(date);
            list.add(time);
        }
        return list;
    }
}
